package com.one.blocks.security.authz;


import com.one.blocks.security.enums.SecurityExceptionEnum;
import com.one.blocks.security.exception.AuthzException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * @author linfuxin Created on 2022-02-14 11:03:47
 */
@Slf4j
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class AuthorizeAspect {

    private final AuthorizeService authorizeService;

    public AuthorizeAspect(AuthorizeService authorizeService) {
        this.authorizeService = authorizeService;
    }

    @Pointcut(value = "@annotation(org.springframework.security.access.prepost.PreAuthorize)")
    public void authzPointCut() {
    }

    @Before("authzPointCut() && @annotation(preAuthorize)")
    public void checkPermission(PreAuthorize preAuthorize) {
        // 不考虑spring el表达式，直接用value
        if (!authorizeService.hasPermission(preAuthorize.value())) {
            throw new AuthzException(SecurityExceptionEnum.NO_PERMISSION);
        }
    }
}